package com.bdqn.t382.answer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SimpleContainer {
    // 保存所有的类型和对应的实例
    private Map<Class<?>, Object> beans = new HashMap<>();

    // 添加 Bean 到容器中
    public void addBean(Class<?> beanClass) {
        try {
            Object beanInstance = beanClass.getDeclaredConstructor().newInstance();
            beans.put(beanClass, beanInstance);
            injectDependencies(beanInstance); // 自动装配依赖
        } catch (Exception e) {
            throw new RuntimeException("添加bean失败: " + beanClass.getName(), e);
        }
    }

    // 自动装配 @Autowired 注解的字段
    public void injectDependencies(Object bean) {
        Class<?> beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Autowired.class)) {
                Class<?> fieldType = field.getType();
                Object fieldInstance = beans.get(fieldType);

                if (fieldInstance == null) {
                    throw new RuntimeException("未找到类型的bean: " + fieldType.getName());
                }

                field.setAccessible(true); // 确保私有字段可以访问
                try {
                    field.set(bean, fieldInstance); // 注入依赖
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("注入依赖项失败: " + field.getName(), e);
                }
            }
        }
    }

    // 根据类型获取 Bean
    public <T> T getBean(Class<T> beanClass) {
        return beanClass.cast(beans.get(beanClass));
    }
}
